package com.yunxin.admin.system.api.system;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yunxin.admin.system.application.RoleQueryService;
import com.yunxin.admin.system.domain.model.user.UserMerchantRepository;
import com.yunxin.admin.system.infra.common.constant.SecurityConstants;
import com.yunxin.admin.system.infra.framework.resubmit.Resubmit;
import com.yunxin.admin.system.infra.framework.security.util.SecurityUtils;
import com.yunxin.admin.system.infra.persistence.entity.SysUserRoleDO;
import com.yunxin.common.result.PageResult;
import com.yunxin.common.result.Result;
import com.yunxin.core.admin.service.AdminUserTeamShipService;
import com.yunxin.core.application.dto.merchant.MerchantDetailDTO;
import com.yunxin.core.application.dto.merchant.MerchantListDTO;
import com.yunxin.core.application.dto.team.*;
import com.yunxin.core.application.service.MerchantQueryAdminService;
import com.yunxin.core.application.service.TeamService;
import com.yunxin.core.domain.model.team.Team;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 团队控制器
 *
 * @author yk°
 * @since 2024-3-30
 */
@Tag(name = "02.团队接口")
@RestController
@RequestMapping("/api/v1/team")
@RequiredArgsConstructor
public class SysTeamController {

    private final TeamService teamService;

    private final UserMerchantRepository userMerchantRepository;

    private final RoleQueryService roleQueryService;

    private final MerchantQueryAdminService merchantQueryAdminService;

    @Autowired
    private AdminUserTeamShipService adminUserTeamShipService;

    @Operation(summary = "团队分页列表", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @GetMapping("/page")
    public PageResult<Team> getTeamPage(@ParameterObject TeamPageCommand command) {
        // 每个商户只能看到自己的团队
        if (!SecurityUtils.X.isRoot()){
            Long userId = SecurityUtils.X.getUser().getUserId();
            List<Long> roleIds = roleQueryService.getRoleListByUserId(userId).stream().map(SysUserRoleDO::getRoleId).toList();
            if (!roleIds.isEmpty()) {
                if (roleIds.contains(1L)) {
                    return PageResult.success(null, 0);
                }
            }
            if (!SecurityUtils.X.isBokeMerchantUser()) {
                return PageResult.success(null, 0);
            }
            Long merchantId = userMerchantRepository.selectMerchantIdByUserId(userId);
            command.setMerchantId(merchantId);
        }
        IPage<Team> result = teamService.getTeamPage(command);
        return PageResult.success(result.getRecords(), result.getTotal());
    }

    @Operation(summary = "商户下拉列表", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @GetMapping("/merchantList")
    public Result<List<MerchantListDTO>> merchantList(@RequestParam(value = "merchantName",required = false)String merchantName) {
        List<MerchantListDTO> merchantListDTOS = new ArrayList<>();
        if (SecurityUtils.X.isRoot()){
            merchantListDTOS = merchantQueryAdminService.selectList(merchantName);
        }else {
            Long userId = SecurityUtils.X.getUser().getUserId();
            Long merchantId = userMerchantRepository.selectMerchantIdByUserId(userId);
            MerchantDetailDTO merchantDetail = merchantQueryAdminService.getMerchantDetail(merchantId);
            MerchantListDTO merchantListDTO=new MerchantListDTO();
            BeanUtils.copyProperties(merchantDetail,merchantListDTO);
            merchantListDTOS.add(merchantListDTO);
        }
        return Result.success(merchantListDTOS);
    }

    @Operation(summary = "团队下拉列表", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @GetMapping("/list")
    public Result<List<Team>> getTeamList(@RequestParam(value = "merchantId",required = false)Long  merchantId) {
        if (!SecurityUtils.X.isRoot()){
            Long userId = SecurityUtils.X.getUser().getUserId();
            if (SecurityUtils.X.isBokeMerchantUser()) {
                //商户管理员
                List<Long> listByUserId = roleQueryService.getRoleListByUserId(userId).stream().map(SysUserRoleDO::getRoleId).toList();
                if (!listByUserId.isEmpty()) {
                    if (listByUserId.contains(1L)) {
                        return Result.success();
                    }
                }
                List<Team> result = teamService.getTeamList(userMerchantRepository.selectMerchantIdByUserId(userId));
                return Result.success(result);
            }
            //团队管理员 业务员 话务员只能看自己的团队
            List<Team> result = teamService.getTeamListByUserId(userId);
            return Result.success(result);
        }else {
            List<Team> result = new ArrayList<>();
            if (!ObjectUtils.isEmpty(merchantId)){
                result = teamService.getTeamList(merchantId);
            }
            return Result.success(result);
        }
    }

    @Operation(summary = "企微下拉框", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/wechatInfoList")
    @Resubmit
    public Result<List<WechatInfoVO>> wechatInfoList(@RequestParam(value = "corpName",required = false)String  corpName) {
        List<WechatInfoVO> wechatInfoVOS = teamService.wechatInfoList(corpName);
        return Result.success(wechatInfoVOS);
    }

    @Operation(summary = "团队信息添加", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/add")
    @PreAuthorize("@ss.hasPerm('business:team:add')")
    @Resubmit
    public Result<Boolean> addTeam(@RequestBody @Validated TeamAddDTO dto) {
        dto.setCreator(SecurityUtils.X.getUser().getUsername());
        Long userId = SecurityUtils.X.getUser().getUserId();
        Long merchantId = userMerchantRepository.selectMerchantIdByUserId(userId);
        dto.setMerchantId(merchantId);
        boolean result = teamService.add(dto);
        return Result.judge(result);
    }

    @Operation(summary = "团队信息修改", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/edit")
    @PreAuthorize("@ss.hasPerm('business:team:edit')")
    @Resubmit
    public Result<Boolean> editTeam(@RequestBody @Validated TeamEditDTO dto) {
        dto.setEditor(SecurityUtils.X.getUser().getUsername());
        Long userId = SecurityUtils.X.getUser().getUserId();
        Long merchantId = userMerchantRepository.selectMerchantIdByUserId(userId);
        dto.setMerchantId(merchantId);
        boolean result = teamService.edit(dto);
        return Result.judge(result);
    }

    @Operation(summary = "团队状态修改", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/edit/status")
    @PreAuthorize("@ss.hasPerm('business:team:edit')")
    @Resubmit
    public Result<Boolean> editTeamStatus(@RequestParam("id") Integer id,
                                          @RequestParam("status") Integer status) {
        Team team = new Team();
        team.setEditor(SecurityUtils.X.getUser().getUsername());
        team.setId(id);
        team.setStatus(status);
        boolean result = teamService.editTeamStatus(team);
        if(status==2){
            adminUserTeamShipService.updateReceivingStatusByTeamId(new ArrayList<>(Arrays.asList(id)));
        }
        return Result.judge(result);
    }

    @Operation(summary = "删除团队", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/delete")
    @PreAuthorize("@ss.hasPerm('business:team:delete')")
    @Resubmit
    public Result<Boolean> delete(@RequestBody TeamDeleteDTO dto) {
        boolean result = teamService.delete(dto);
        adminUserTeamShipService.updateReceivingStatusByTeamId(dto.getTeamIds());
        return Result.judge(result);
    }
}
